package cn.hhy.hrm.config;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

import javax.security.sasl.AuthenticationException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsAuthFilter extends AbstractAuthenticationProcessingFilter {
    //手机号在请求中的参数名
    public static final String PHONE_KEY = "phone";
    //请求方式
    private boolean postOnly = true;

    public SmsAuthFilter() {
        //验证码登录地址
        super(new AntPathRequestMatcher("/smslogin", "POST"));
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        //1.只能支持Post请求
        if (postOnly && !httpServletRequest.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + httpServletRequest.getMethod());
        }
        //2.获取手机号
        String phone = httpServletRequest.getParameter(PHONE_KEY);
        //3.判断手机号
        if(!StringUtils.hasLength(phone)){
            throw new UsernameNotFoundException("无效的用户名");
        }
        //4.封装Token对象
        SmsAuthToken authRequest = new SmsAuthToken(  phone, null);
        //5.设置Details
        setDetails(httpServletRequest, authRequest);
        //6.调用认证管理器执行认证
        return this.getAuthenticationManager().authenticate(authRequest);
    }
    protected void setDetails(HttpServletRequest request,
                              SmsAuthToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}